Как создать службу WebAPI, которая принимает объект со свойством вложения документа? - PullRequest
1 голос
/ 30 октября 2019

Я хотел бы создать конечную точку WebAPI, которая принимает объект, содержащий свойство для документов, которые могут быть прикреплены. Эта конечная точка должна обслуживать запросы JSON и XML, и не знать, как это работает. Я посмотрел вокруг, но не могу найти хороший пример для спецификации, которую я ищу. Ниже приведен тип решения, в котором мне нужна помощь:

Объекты модели:

public class User
{
    public User(){
        Documents = new List<Document>();
    }
    public int UserId {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string Employee {get;set;}
    public List<Document> Documents {get;set;} //e.g. Identity Document, Certifications etc
}
public class Document{
    public int DocumentId {get;set;}
    public string Name {get;set;}
    public string Extension {get;set;}
    public byte[] Data {get;set;}
}

Конечная точка контроллера WebAPI:

[HttpPost]
public IHttpActionResult(User user){
   ... WHAT TYPE OF CODE DO I NEED HERE ...
}

Основной вопрос заключается в том, какклиент также отправляет сообщение на эту конечную точку, если вы можете привести пример? Правильный ли мой модельный объект? Как можно отправить данные со стороны клиента с помощью запроса xml, поскольку данные байтового массива несовместимы с xml?

1 Ответ

1 голос
/ 01 ноября 2019

Это внутренний код (контроллер WebApi).

    [HttpPost]
    public IHttpActionResult AcceptUserInfoAndFiles()
    {
        User userInfo = new User();
        var httpContext = HttpContext.Current;
        NameValueCollection nvc = HttpContext.Current.Request.Form;

        // Fill User data ....
        userInfo.UserId=Convert.ToInt32(nvc["UserId"]);
        userInfo.FirstName = nvc["FirstName"];

        List<Document> documents = new List<Document>();
        // Check for any uploaded file  
        if (httpContext.Request.Files.Count > 0)
        {
            //Loop through uploaded files                  
            for (int i = 0; i < httpContext.Request.Files.Count; i++)
            {
                HttpPostedFile httpPostedFile = httpContext.Request.Files[i];
                if (httpPostedFile != null)
                {
                    // Get data in byte array
                    byte[] fileData = null;
                    using (var binaryReader = new BinaryReader(httpPostedFile.InputStream))
                    {
                        fileData = binaryReader.ReadBytes(httpPostedFile.ContentLength);
                    }
                    documents.Add(new Document
                    {
                        DocumentId = 1, //Generate your document id
                        Name = httpPostedFile.FileName, // Remove extension if you want to store only name
                        Extension = System.IO.Path.GetExtension(httpPostedFile.FileName), // Get file extension
                        Data = fileData
                    });

                }
            }
        }
        userInfo.Documents = documents;

        return Ok();
    }

Вот пример кода переднего плана в jquery и html

    <div>
    <form method="post" action="http://localhost:59462/Api/Values" enctype="multipart/form-data" id="formUpload">
        <div>
            <label for="files">Files</label>
            <input type="file" id="files" name="files" multiple="multiple" />
        </div>
        <button type="button" id="buttonUpload">Upload files</button>
    </form>
</div>
<script>
$(document).ready(function () {

    $('#buttonUpload').on('click', function () {
        var model = new FormData();
        // Get User properties.
        model.append('UserId', 1); // Get from UI
        model.append('FirstName', "Sam"); // Get from UI
        var files = $("#files").get(0).files;

        // Add the uploaded file to the form data collection
        if (files.length > 0) {
            for (f = 0; f < files.length; f++) {
                model.append("UploadedImage", files[f]);
            }
        }

        // Ajax upload
        $.ajax({
            type: "POST",
            url: $("#formUpload").attr("action"),
            contentType: false,
            processData: false,
            data: model
        });
    });
});
</script>

Вот ссылки на ссылки: https://dejanstojanovic.net/aspnet/2018/february/multiple-file-upload-with-aspnet-webapi/ Опубликовать JSON с данными И файлом в WebApi - jQuery / MVC

...