我想验证USPS的给定地址(地址,城市,州,邮政编码),如果提供的地址是有效地址,则返回结果。如果不是有效地址,则返回无效地址。
所以我怎样才能在C#.Net中做到这一点。
答案 0 :(得分:14)
美国邮政服务(USPS)确实通过其地址信息API提供此服务:
以下是Code Project文章/库如何在.NET中使用此服务:
注意强>
答案 1 :(得分:10)
来自here
///Create a new instance of the USPS Manager class
///The constructor takes 2 arguments, the first is
///your USPS Web Tools User ID and the second is
///true if you want to use the USPS Test Servers.
USPSManager m = new USPSManager("YOUR_USER_ID", true);
Address a = new Address();
a.Address2 = "6406 Ivy Lane";
a.City = "Greenbelt";
a.State = "MD";
///By calling ValidateAddress on the USPSManager object,
///you get an Address object that has been validated by the
///USPS servers
Address validatedAddress = m.ValidateAddress(a);
注意:出于某种原因,您需要将实际地址作为地址2。如果您尝试将Address1设置为“6406 Ivy Lane”,它将失败。地址1显然是公寓或套房号码。 礼貌Simon Weaver以下评论。
答案 2 :(得分:5)
如果我可以在这里讨论 - 我曾经在SmartyStreets的地址验证行业工作,SmartyStreets是这些服务的CASS认证供应商。
首先请注意,虽然USPS是地址数据的权威,但他们的强项不是维护API并提供支持。另外,请务必记下您签署的协议:
- 用户同意仅使用USPS网站,API和USPS数据来促进USPS航运交易。
因此,除非您通过使用API邮寄或运送USPS,否则根本不同意使用API。你遇到的其他问题之一就是寻找更好的解决方案 - 如果我是你的话。
无论如何,实际上有很多。我会让你做自己的研究,但我当然会建议我曾经做过一个名为LiveAddress的工作。它是免费的,返回的数据更多,比USPS的API更可靠。
更新: Here's some C# code examples on GitHub可能会有用。
答案 3 :(得分:-1)
服务对象地址验证Web服务可以根据USPS确定地址是否有效。以下是几个C#示例(RESTful请求和SOAP请求):
有礼貌的请求
string mainURL = "https://trial.serviceobjects.com/AV3/api.svc/GetBestMatchesJson/" + businessName + "/" + address + "/" + address2 + "/" + city + "/" + state + "/" + zip + "/" + licenseKey;
AV3Response result = null;
HttpWebRequest request = WebRequest.Create(mainURL ) as HttpWebRequest;
request.Timeout = 5000;//timeout for get operation
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
//parse response
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(AV3Response));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
result = objResponse as AV3Response;
//processing result
if (result.error == null)
{
//process result
}
else
{
//process error
}
另一种选择是使用wsdl并发出SOAP请求。
SOAP请求
//Add a service to your application https://trial.serviceobjects.com/av3/api.svc/
AV3Client_Primary = new AddressValidation3Client("DOTSAddressValidation3");
response = AV3Client_Primary.GetBestMatches(Business, Address, Address2, City, State, PostalCode, licenseKey);
响应字段将包含有关地址有效性的信息。 DPV分数可用于确定地址是否可交付,不可交付或接近正确但缺少一些重要信息(apt,ste,rr#)。
如果您想了解有关服务输出的更多信息,可以查看here