HttpPost不能在C#中工作,但在Android中可以正常工作

时间:2017-04-05 11:21:25

标签: c# android rest uwp httpclient

我正在为休息服务做一个HttpPost来撤销许可证。在Android上,请求完美无缺。但是当用c#做帖子时,我得到了回复

  

"在控制器上找不到与请求匹配的操作"

在Android中:

@Override
protected String doInBackground(String... params) 
{
        String request = serverUrl + "api/Public/RemoveInstall?DeviceID="+deviceId+"&UserID="+m_userID;
        try {
            if(!isNetworkAvailable())
            {
                return "no_accesToken";
            }
            else
            {
                URL url = new URL(request);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setDoOutput(false);
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("charset", "utf-8");
                conn.setConnectTimeout(1500);
                conn.setUseCaches(false);
                conn.connect();

                ...
}

上面的代码效果很好,但在c#中它不会起作用:

public async Task<bool> RevokeLicenseAsync(string userId)
{
        if (!IsInternetConnected())
        {
            errorMsg = "No internet connection";
            return false;
        }

        string deviceId = GetDeviceID();

        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("DeviceID", deviceId));
        postData.Add(new KeyValuePair<string, string>("UserID", userId));

        //the header arguments "ContentType" and "ContentLength are filled in automatically"
        var formContent = new FormUrlEncodedContent(postData);

        if (!String.IsNullOrEmpty(token)) 
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(serverUrl);

                using (var response = await httpClient.PostAsync("api/Public/RemoveInstall",formContent))
                {

2 个答案:

答案 0 :(得分:1)

你可以改变如下

@shopping_list = ShoppingList.new(shopping_list_params)
@shopping_list.save

如果您使用一个类型参数进行发布请求,则必须指定FromBody或FormUri

答案 1 :(得分:0)

在Android请求中,您在网址中发布参数,但在第二个中,您将其发布在正文中。

如果第一个有效,那么尝试对第二个做同样的事情。

var requestUri = string.Format("api/Public/RemoveInstall?DeviceID={0}&UserID={1}", deviceId, userId);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
using (var httpClient = new HttpClient()) {
    httpClient.BaseAddress = new Uri(serverUrl);
    using (var response = await httpClient.SendAsync(request)) {
        //...other code