IT박스

WebAPI 다중 Put / Post 매개 변수

itboxs 2020. 6. 25. 22:02
반응형

WebAPI 다중 Put / Post 매개 변수


WebAPI 컨트롤러에 여러 매개 변수를 게시하려고합니다. 하나의 매개 변수는 URL에서, 다른 하나는 본문에서입니다. URL은 다음과 같습니다./offers/40D5E19D-0CD5-4FBD-92F8-43FDBB475333/prices/

내 컨트롤러 코드는 다음과 같습니다.

public HttpResponseMessage Put(Guid offerId, OfferPriceParameters offerPriceParameters)
{
    //What!?
    var ser = new DataContractJsonSerializer(typeof(OfferPriceParameters));
    HttpContext.Current.Request.InputStream.Position = 0;
    var what = ser.ReadObject(HttpContext.Current.Request.InputStream);

    return new HttpResponseMessage(HttpStatusCode.Created);
}

본문의 내용은 JSON입니다.

{
    "Associations":
    {
        "list": [
        {
            "FromEntityId":"276774bb-9bd9-4bbd-a7e7-6ed3d69f196f",
            "ToEntityId":"ed0d2616-f707-446b-9e40-b77b94fb7d2b",
            "Types":
            {
                "list":[
                {
                    "BillingCommitment":5,
                    "BillingCycle":5,
                    "Prices":
                    {
                        "list":[
                        {
                            "CurrencyId":"274d24c9-7d0b-40ea-a936-e800d74ead53",
                            "RecurringFee":4,
                            "SetupFee":5
                        }]
                    }
                }]
            }
        }]
    }
}

기본 바인딩이 offerPriceParameters내 컨트롤러 인수에 바인딩 할 수없는 이유는 무엇입니까? 항상 null로 설정됩니다. 그러나를 사용하여 신체에서 데이터를 복구 할 수 DataContractJsonSerializer있습니다.

또한 FromBody인수 속성 을 사용하려고 하지만 작동하지 않습니다.


[HttpPost]
public string MyMethod([FromBody]JObject data)
{
    Customer customer = data["customerData"].ToObject<Customer>();
    Product product = data["productData"].ToObject<Product>();
    Employee employee = data["employeeData"].ToObject<Employee>();
    //... other class....
}

참조 사용

using Newtonsoft.Json.Linq;

JQuery Ajax에 대한 요청 사용

var customer = {
    "Name": "jhon",
    "Id": 1,
};
var product = {
    "Name": "table",
    "CategoryId": 5,
    "Count": 100
};
var employee = {
    "Name": "Fatih",
    "Id": 4,
};

var myData = {};
myData.customerData = customer;
myData.productData = product;
myData.employeeData = employee;

$.ajax({
    type: 'POST',
    async: true,
    dataType: "json",
    url: "Your Url",
    data: myData,
    success: function (data) {
        console.log("Response Data ↓");
        console.log(data);
    },
    error: function (err) {
        console.log(err);
    }
});

기본적으로 WebAPI는 여러 POST 매개 변수의 바인딩을 지원하지 않습니다. Colin이 지적한 것처럼 내 블로그 게시물 에는 몇 가지 제한 사항이 있습니다 .

사용자 지정 매개 변수 바인더를 만들어 해결 방법이 있습니다. 이 작업을 수행하는 코드는 추악하고 복잡하지만 블로그에 자세한 설명과 함께 코드를 게시하여 프로젝트에 연결할 수 있습니다.

여러 간단한 POST 값을 ASP.NET 웹 API에 전달


속성 라우팅을 사용중인 경우 [FromUri] 및 [FromBody] 속성을 사용할 수 있습니다.

예:

[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id,  [FromBody()] Product product)
{
  // Add product
}

Json 객체를 HttpPost 메소드로 전달하고 동적 객체로 구문 분석합니다. 잘 작동합니다. 이것은 샘플 코드입니다.

ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
       "AppInstanceID":"100",
       "ProcessGUID":"072af8c3-482a-4b1c‌​-890b-685ce2fcc75d",
       "UserID":"20",
       "UserName":"Jack",
       "NextActivityPerformers":{
           "39‌​c71004-d822-4c15-9ff2-94ca1068d745":[{
                 "UserID":10,
                 "UserName":"Smith"
           }]
       }}
...

webapi :

[HttpPost]
public string DoJson2(dynamic data)
{
   //whole:
   var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString()); 

   //or 
   var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());

   var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());

   string appName = data.AppName;
   int appInstanceID = data.AppInstanceID;
   string processGUID = data.ProcessGUID;
   int userID = data.UserID;
   string userName = data.UserName;
   var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());

   ...
}

복잡한 객체 유형은 객체, 배열 및 사전 일 수 있습니다.


간단한 매개 변수 클래스를 사용하여 게시물에 여러 매개 변수를 전달할 수 있습니다.

public class AddCustomerArgs
{
    public string First { get; set; }
    public string Last { get; set; }
}

[HttpPost]
public IHttpActionResult AddCustomer(AddCustomerArgs args)
{
    //use args...
    return Ok();
}

https://github.com/keith5000/MultiPostParameterBinding 에서 MultiPostParameterBinding 클래스를 사용하여 여러 POST 매개 변수를 허용 할 수 있습니다.

그것을 사용하려면 :

1) 소스 폴더 에서 코드를 다운로드 하여 웹 API 프로젝트 또는 솔루션의 다른 프로젝트에 추가하십시오.

2) 여러 POST 매개 변수를 지원해야하는 조치 메소드에서 속성 [MultiPostParameters]사용하십시오 .

[MultiPostParameters]
public string DoSomething(CustomType param1, CustomType param2, string param3) { ... }

3) GlobalConfiguration.Configure (WebApiConfig.Register)를 호출 하기 전에 Global.asax.cs에서이 줄을 Application_Start 메소드에 추가하십시오 .

GlobalConfiguration.Configuration.ParameterBindingRules.Insert(0, MultiPostParameterBinding.CreateBindingForMarkedParameters);

4) 클라이언트가 매개 변수를 개체의 속성으로 전달하도록합니다. DoSomething(param1, param2, param3)메소드의 JSON 오브젝트 예제 는 다음과 같습니다.

{ param1:{ Text:"" }, param2:{ Text:"" }, param3:"" }

JQuery 예 :

$.ajax({
    data: JSON.stringify({ param1:{ Text:"" }, param2:{ Text:"" }, param3:"" }),
    url: '/MyService/DoSomething',
    contentType: "application/json", method: "POST", processData: false
})
.success(function (result) { ... });

자세한 내용 은 링크방문 하십시오.

면책 조항 : 나는 링크 된 리소스와 직접 관련이 있습니다.


좋은 질문과 의견-답글에서 많은 것을 배웠습니다. :)

추가적인 예로서, 바디와 루트를 혼합 할 수도 있습니다.

[RoutePrefix("api/test")]
public class MyProtectedController 
{
    [Authorize]
    [Route("id/{id}")]
    public IEnumerable<object> Post(String id, [FromBody] JObject data)
    {
        /*
          id                                      = "123"
          data.GetValue("username").ToString()    = "user1"
          data.GetValue("password").ToString()    = "pass1"
         */
    }
}

이런 식으로 전화 :

POST /api/test/id/123 HTTP/1.1
Host: localhost
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer x.y.z
Cache-Control: no-cache

username=user1&password=pass1


enter code here

이 경우 routeTemplate의 모양은 무엇입니까?

이 URL을 게시했습니다.

/offers/40D5E19D-0CD5-4FBD-92F8-43FDBB475333/prices/

이것이 작동하기 위해서는 다음과 같은 라우팅이 필요합니다 WebApiConfig.

routeTemplate: {controller}/{offerId}/prices/

다른 가정은 다음과 같습니다.-컨트롤러를 호출 OffersController합니다. -요청 본문에 전달하는 JSON 객체는 OfferPriceParameters파생 유형이 아닌 유형입니다.이 컨트롤러를 방해 할 수있는 다른 메소드가 없습니다 (그렇다면 주석 처리하고 무엇을 참조하십시오) 발생)

Filip이 언급했듯이 '0 %의 수락 률'로 답변을 받기 시작하면 사람들이 시간을 낭비한다고 생각할 수 있으므로 질문에 도움이 될 것입니다.


If you don't want to go ModelBinding way, you can use DTOs to do this for you. For example, create a POST action in DataLayer which accepts a complex type and send data from the BusinessLayer. You can do it in case of UI->API call.

Here are sample DTO. Assign a Teacher to a Student and Assign multiple papers/subject to the Student.

public class StudentCurriculumDTO
 {
     public StudentTeacherMapping StudentTeacherMapping { get; set; }
     public List<Paper> Paper { get; set; }
 }    
public class StudentTeacherMapping
 {
     public Guid StudentID { get; set; }
     public Guid TeacherId { get; set; }
 }

public class Paper
 {
     public Guid PaperID { get; set; }
     public string Status { get; set; }
 }

Then the action in the DataLayer can be created as:

[HttpPost]
[ActionName("MyActionName")]
public async Task<IHttpActionResult> InternalName(StudentCurriculumDTO studentData)
  {
     //Do whatever.... insert the data if nothing else!
  }

To call it from the BusinessLayer:

using (HttpResponseMessage response = await client.PostAsJsonAsync("myendpoint_MyActionName", dataof_StudentCurriculumDTO)
  {
     //Do whatever.... get response if nothing else!
  }

Now this will still work if I wan to send data of multiple Student at once. Modify the MyAction like below. No need to write [FromBody], WebAPI2 takes the complex type [FromBody] by default.

public async Task<IHttpActionResult> InternalName(List<StudentCurriculumDTO> studentData)

and then while calling it, pass a List<StudentCurriculumDTO> of data.

using (HttpResponseMessage response = await client.PostAsJsonAsync("myendpoint_MyActionName", List<dataof_StudentCurriculumDTO>)

Request parameters like

enter image description here

Web api Code be like

public class OrderItemDetailsViewModel
{
    public Order order { get; set; }
    public ItemDetails[] itemDetails { get; set; }
}

public IHttpActionResult Post(OrderItemDetailsViewModel orderInfo)
{
    Order ord = orderInfo.order;
    var ordDetails = orderInfo.itemDetails;
    return Ok();
}

You can get the formdata as string:

    protected NameValueCollection GetFormData()
    {
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        Request.Content.ReadAsMultipartAsync(provider);

        return provider.FormData;
    }

    [HttpPost]
    public void test() 
    {
        var formData = GetFormData();
        var userId = formData["userId"];

        // todo json stuff
    }

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

참고URL : https://stackoverflow.com/questions/14407458/webapi-multiple-put-post-parameters

반응형