簡體   English   中英

在 .net 核心 controller 中使用相同的路由處理 GET 和 POST 請求

[英]Handle both GET and POST request with same route in .net core controller

我正在嘗試使用相同的路由在同一個 controller 中處理 GET 和 POST,因為我有某些 rest 調用,數據可能使用 GET 或 POST 來調用相同的端點....

這適用於 GET:

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
    [HttpGet("GetAccount")]
    [Route("api/accounts/GetAccount")]
    public string GetAccount(string accountID)
    {
        return "echoing accountID: " + accountID;
    }
}

這適用於 POST:

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
    [HttpPost("GetAccount")]
    [Route("api/accounts/GetAccount")]
    public string GetAccount([FromForm] string accountID)
    {
        return "echoing accountID: " + accountID;
    }
}

但這不會從 POST 返回值:

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
    [HttpPost("GetAccount"),HttpGet("GetAccount")]
    [Route("api/accounts/GetAccount")]
    public string GetAccount(string accountID)
    {
        // accountID is NULL when doing a POST, but is correct for a GET...
        return "echoing accountID: " + accountID;
    }
}

在上面的示例中,GET 請求工作正常,但在執行 POST 時,參數 accountID 為 NULL,因為我刪除了[FromForm]以使其與 GET 一起使用。

有什么方法可以將它組合成一條路線嗎?

這是針對 .net 核心 5.0 站點的....

我如何從 javascript 發布到端點的示例:

$.ajax({
   url: '/api/accounts/GetAccount',
   data: {
      accountID: 'abcdefg'
   },
   type: 'POST',
   dataType: 'JSON',
   contentType: "application/x-www-form-urlencoded; charset=UTF-8" 
})
   .done(function (result) {
      // verified that the result is NULL
      console.log(result);
   })
   .fail(function () {
      alert("ERROR");;
   })
   .always(function () {
      alert("DONE");
   });

這是我完整的啟動文件(以防我沒有正確注冊):

public class Startup
{
   public Startup(IConfiguration configuration)
   {
      Configuration = configuration;
   }

   public IConfiguration Configuration { get; }

   public void ConfigureServices(IServiceCollection services)
   {
      services.AddSession();
      services.AddHttpContextAccessor();
      services.AddRazorPages();
      services.AddControllers();
      services.AddControllers().AddNewtonsoftJson();
      services.AddControllersWithViews();
   }

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   {
      app.UseSession();
      app.UseExceptionHandler("/Error");
      app.UseHsts();
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseRouting();
      app.UseAuthentication();
      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
         endpoints.MapRazorPages();
         endpoints.MapControllers();
      });
    }
}

謝謝!

您可以嘗試更改您的代碼,如下所示:

    [HttpPost("GetAccount"), HttpGet("GetAccount")]
    [Route("api/accounts/GetAccount")]
    public string GetAccount()        
    {
        if ("GET" == HttpContext.Request.Method)
        {
            //if your `accountID` is fromquery in your get method.
            string accountID = HttpContext.Request.Query["accountID"];
            return "echoing accountID: " + accountID;
        }

        else if ("POST" == HttpContext.Request.Method)
        {
            string accountID = HttpContext.Request.Form["accountID"];
            return "echoing accountID: " + accountID;
        }
        else
        {
            return "error";
        }
    }

另外,我認為您的代碼可能沒有問題。 發出 post 方法時,您應該檢查您的 accountID 參數。

更新

api controller的默認屬性是[FromBody],所以必須指定源。如果不想指定為[FromForm],可以通過querystring傳遞數據。

$.ajax({
            url: '/api/values/GetAccount?accountID=abcdefg',
            type: 'POST',
            dataType: 'JSON',
            contentType: "application/x-www-form-urlencoded; charset=UTF-8"
        })
            .done(function (result) {
                // verified that the result is NULL
                console.log(result.message);
            })
            .fail(function () {
                alert("ERROR");;
            })
            .always(function () {
                alert("DONE");
            });
    });

行動:

    [HttpPost("GetAccount"), HttpGet("GetAccount")]
    [Route("api/accounts/GetAccount")]
    public IActionResult GetAccount(string accountID)
    {
        string message = "echoing accountID: " + accountID;
        // accountID is NULL when doing a POST, but is correct for a GET...
        return new JsonResult(new { message = message });
    }

您是否嘗試過創建兩個單獨的功能。 一個用於 GET,另一個用於 POST? 您仍然可以將Route屬性設置為相同,但它將是 HTTP 方法,該方法來自消費者,它將確定將調用哪個方法。

此外,您需要使用[FromBody]屬性來訪問隨請求發送的任何有效負載。

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
    [HttpGet]
    [Route("api/accounts/GetAccount")]
    public string GetAccount([FromBody] request)
    {
        return "echoing accountID: " + request.accountID;
    }

    [HttpPost]
    [Route("api/accounts/GetAccount")]
    public string CreateAccount([FromBody] request)
    {
        return "echoing accountID: " + request.accountID;
    }
}

編輯

您可能需要將[FromQuery]用於 GET 端點,將[FromBody]用於 POST 端點。

然后對於您的 GET,您的 URL 將使用查詢參數而不是數據有效負載。 例如/api/accounts/GetAccount?accountID=12345

[Produces("application/json")]
[ApiController]
public class AccountController : ControllerBase
{
    [HttpGet]
    [Route("api/accounts/GetAccount")]
    public string GetAccount([FromQuery] request)
    {
        return "echoing accountID: " + request.accountID;
    }

    [HttpPost]
    [Route("api/accounts/GetAccount")]
    public string CreateAccount([FromBody] request)
    {
        return "echoing accountID: " + request.accountID;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM