在C#和Asp.net的Web API URL编码 [英] URL Encoding in c# and Asp.net web api
问题描述
我有一个的ASP.NET Web API
接收Web请求,并返回的Json
数据。
浏览此网址:
http://1.2.3.4/api1/api/values/mypartname
将返回以下JSON字符串:
{
\零件名称\:\mypartname \,
\PartDes \:\53.6X53.6APA / ALIM1NOTPAK \,
\PartLocation \:\A36 \
}
但发送包含空格或引号一部分像这样的名字的时候: http://1.2.3.4/api1/api/values/my一部分呐我
我获得 404 - 文件或目录未找到
错误
。
我消耗 JSON
与 .NET 4控制台应用程序
像这样:
静态无效的主要(字串[] args)
{
尝试
{
字符串零件名称=带56 3M 3/4 \;
WebRequest的WR = WebRequest.Create(http://1.2.3.4/api1/api/values/+
HttpUtility.UrlEn code(零件名称));
wr.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse HWR =(HttpWebResponse)wr.GetResponse();
流式传输的数据流= hwr.GetResponseStream();
StreamReader的读者=新的StreamReader(数据流);
JSON字符串= reader.ReadToEnd();
//一些JSON解析功能
DES(JSON);
reader.Close();
dataStream.Close();
hwr.Close();
}
赶上(例外前)
{
Console.WriteLine(ex.Message);
}
最后
{
Console.ReadKey();
}
}
抛出异常,在这一行: HttpWebResponse HWR =(HttpWebResponse)wr.GetResponse();
和异常信息是:远程服务器返回错误:(404)未找到
我做得不对的 mypartname
?我也试图根据这个手动替换有问题的字符: HTML URL编码参考一>,并使用此功能: Uri.EscapeDataString(零件名称)
,但没有运气
修改
这是routeConfig定义:
routes.IgnoreRoute({}资源个.axd / {* PATHINFO});
routes.MapRoute(
名称:默认,
网址:{控制器} / {行动} / {ID},
默认:新{控制器=主页,行动=索引,ID = UrlParameter.Optional}
);
和API的GET方法:
//获取API /价值/ 5
公共字符串获取(串号)
{
名单<假>假人=新名单,其中哑GT;();
字符串CON =用户ID = SA; +
密码= 1234+
服务器= someServer \\ someInstance; +
数据库=游戏;+
连接超时= 30;
// SqlConnection的sqlConn =新的SqlConnection(CON);
使用(SqlConnection的sqlconn =新的SqlConnection(CON))
{
sqlconn.Open();
StringBuilder的SB =新的StringBuilder();
sb.Append(选择PART.PARTNAME,PART.PARTDES,PARTPARAMA.LOCATION);
sb.Append(来自第LEFT JOIN PARTPARAMA);
sb.Append(ON PART.PART = PARTPARAMA.PARTPARAM);
sb.Append(WHERE PART.PARTNAME = @part);
使用(CMD的SqlCommand =新的SqlCommand(sb.ToString(),sqlconn))
{
cmd.Parameters.AddWithValue(部分,身份证);
SqlDataReader的SDR = cmd.ExecuteReader();
而(sdr.Read())
{
dummies.Add(新的虚拟
{
零件名称= sdr.IsDBNull(0)? 未知:sdr.GetString(0)
PartDes = sdr.IsDBNull(1)? 未知:sdr.GetString(1)
PartLocation = sdr.IsDBNull(2)? 未知:sdr.GetString(2)
});
}
}
}
如果(dummies.Count()大于0)
{
JSON字符串= JsonConvert.SerializeObject(假人[0]);
返回JSON;
}
其他
{
JSON字符串= JsonConvert.SerializeObject(空);
返回JSON;
}
修改 2015年4月10号:
我在这里离开这个答案的人谁发现它在搜索,但凯文低于国和的在Scott Hanselman说这里:
[UrlPathEn code]没有做什么,你觉得它...这种方法是 非常具体的,不良的命名,现在已经是完全过时。
我觉得你的问题,更多的是在零件名称斜杠。 您可以使用处理空间和报价
HttpUtility.UrlPathEn code(零件名称)
而不是 HttpUtility.UrlEn code(零件名称)
。
处理斜杠更成问题。请参见这个帖子了解更多详情。
I have an ASP.NET web api
that receives web requests and returns Json
data.
browsing to this URL:
http://1.2.3.4/api1/api/values/mypartname
will return the following json string:
{
\"PartName\": \"mypartname\",
\"PartDes\": \"53.6X53.6APA/ALIM1NOTPAK\",
\"PartLocation\": \"A36\"
}
but when sending a part name that contains spaces or quotes like this: http://1.2.3.4/api1/api/values/my part na"me
i get a 404 - File or directory not found.
error.
I'm consuming the json
with a .NET 4 Console application
like so:
static void Main(string[] args)
{
try
{
string partName = "TAPE 56 3M 3/4\"";
WebRequest wr = WebRequest.Create("http://1.2.3.4/api1/api/values/" +
HttpUtility.UrlEncode(partName));
wr.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
Stream dataStream = hwr.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
//some json parsing function
des(json);
reader.Close();
dataStream.Close();
hwr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
the exception is thrown at this line:HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
and the exception message is: The remote server returned an error: (404) Not Found.
Am i doing something wrong with the mypartname
? I also tried to manually replace the problematic characters according to this: HTML URL Encoding Reference and using this function:Uri.EscapeDataString(partName)
but with no luck.
EDIT
this is the routeConfig definition:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and the api GET method:
// GET api/values/5
public string Get(string id)
{
List<dummy> dummies = new List<dummy>();
string con = "user id=sa;" +
"password=1234" +
"server=someServer\\someInstance;" +
"database=game; " +
"connection timeout=30";
//SqlConnection sqlConn = new SqlConnection(con);
using (SqlConnection sqlconn = new SqlConnection(con))
{
sqlconn.Open();
StringBuilder sb = new StringBuilder();
sb.Append("SELECT PART.PARTNAME,PART.PARTDES, PARTPARAMA.LOCATION ");
sb.Append("FROM PART LEFT JOIN PARTPARAMA ");
sb.Append("ON PART.PART = PARTPARAMA.PARTPARAM ");
sb.Append("WHERE PART.PARTNAME = @part");
using (SqlCommand cmd = new SqlCommand(sb.ToString(), sqlconn))
{
cmd.Parameters.AddWithValue("part", id);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
dummies.Add(new dummy
{
PartName = sdr.IsDBNull(0) ? "Unknown" : sdr.GetString(0),
PartDes = sdr.IsDBNull(1) ? "Unknown" : sdr.GetString(1),
PartLocation = sdr.IsDBNull(2) ? "Unknown" : sdr.GetString(2)
});
}
}
}
if (dummies.Count() > 0)
{
string json = JsonConvert.SerializeObject(dummies[0]);
return json;
}
else
{
string json = JsonConvert.SerializeObject(null);
return json;
}
EDIT 10 Apr 2015:
I am leaving this answer here for anyone who finds it in a search, however as Kevin states below and Scott Hanselman says here:
[UrlPathEncode] doesn't do what you think it does ... This method was very specific, poorly named, and is now totally obsolete.
I think your problem has more to do with the forward slash in the part name. You can handle the spaces and quotes using
HttpUtility.UrlPathEncode(partName)
instead of HttpUtility.UrlEncode(partName)
.
Handling the forward slash is more problematic. See this post for more details.
这篇关于在C#和Asp.net的Web API URL编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!