我需要传递一个连接的字符串作为web api url [英] I need to pass a concatenated string as a web api url

查看:123
本文介绍了我需要传递一个连接的字符串作为web api url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Xamarin的PCL项目。我需要在web api Url中动态传递设备的IP地址。我的代码如下:



在后面的代码中:



I am developing a PCL Project in Xamarin .I need to pass the IP Address of the device dynamically in the web api Url. My Code is as below:

In the code behind:

string IpAdd = txtIP.Text;

IPAddress = "http://" + IpAdd + ":8124/api/Items/";

MainViewModel.FinalIPAddress = IPAddress;





在我的MainViewModel





In my MainViewModel

public static string FinalIPAddress { get; set; }

public static readonly string WebServiceUrl = System.Net.WebUtility.UrlEncode(FinalIPAddress);



但是我无法解决这个问题。抛出以下异常。



抛出异常:System.Net.Http.Phone.ni.DLL中的'System.InvalidOperationException'附加信息:无效请求URI已提供。请求URI必须是绝对URI或必须设置BaseAddress。



如何解决这个问题?任何帮助将不胜感激。 Thanx提前。



我尝试过:



[已删除]


But I am unable to get through this. The below exception gets thrown.

Exception thrown: 'System.InvalidOperationException' in System.Net.Http.Phone.ni.DLL Additional information: An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

How to go about with this? Any help will be appreciated. Thanx in advance.

What I have tried:

[removed]

推荐答案

我想,你需要使用HttpUtility.UrlEncodeUnicode和HttpUtility.UrlDecode



见下文链接



UrlEncode UrlDecode

I think, you need to use HttpUtility.UrlEncodeUnicode and HttpUtility.UrlDecode

See below links

UrlEncode and UrlDecode


问题是您已将 WebServiceUrl 声明为字段。这意味着初始化程序将在第一次访问类之前运行一次,此时 FinalIPAddress null



更新 FinalIPAddress 属性时,它对<$ c的值没有影响$ c> WebServiceUrl 字段。



尝试将 WebServiceUrl 更改为属性:

The problem is that you've declared WebServiceUrl as a field. That means the initializer will run once, before the first access to the class, at which point your FinalIPAddress will be null.

When you update the FinalIPAddress property, it will have no effect on the value of the WebServiceUrl field.

Try changing WebServiceUrl to a property:
public static string WebServiceUrl
{
    get { return System.Net.WebUtility.UrlEncode(FinalIPAddress); }
}



然而,如果您尝试使用该网址调用 API,而不是将URL作为参数传递给 API,然后您需要删除 UrlEncode 调用:


However, if you're trying to call the API using that URL, rather than passing the URL as a parameter to the API, then you'll need to remove the UrlEncode call:

public static string WebServiceUrl
{
    get { return FinalIPAddress; }
}


这篇关于我需要传递一个连接的字符串作为web api url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆