1.publish RESTful WCF on IIS,and set username/password,you can reference
http://blog.csdn.net/fangxinggood/article/details/6263780,this article instruct you how to add authentication in wcf:
this is source code in Global.asax
View Code
using System;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Routing;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;
namespace StoreRestWcf
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
EnableCrossDmainAjaxCall();
}
private void EnableCrossDmainAjaxCall()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"1728000");
HttpContext.Current.Response.End();
}
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
//RouteTable.Routes.Add(new ServiceRoute("store", new WebServiceHostFactory(), typeof(com.sang.rest.wcf.StoreService)));
RouteTable.Routes.Add(new ServiceRoute("store", new SangSecureWebServiceHostFactory(), typeof(com.sang.rest.wcf.StoreService)));
}
}
public class SangSecureWebServiceHostFactory : WebServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();
return host;
}
public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(constructorString, baseAddresses);
host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();
return host;
}
}
public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
var ctx = WebOperationContext.Current;
var auth = ctx.IncomingRequest.Headers[HttpRequestHeader.Authorization];
if (string.IsNullOrEmpty(auth) || auth != "sang/jw501")
{
ctx.OutgoingResponse.StatusCode = HttpStatusCode.MethodNotAllowed;
return false;
}
return true;
}
}
}
2.in html page,if use jQuery,for example,you add "headers" settings in ajax() method:
View Code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Store state infomation</title>
</head>
<body>
<div id="store_info">
</div>
<script src="../js/jquery-1.6.2.min.js">
</script>
<script src="../js/sang_ui.js">
</script>
<script type="text/javascript">
var wcfAddress = "http://192.168.11.2/rest/store/GetStoreState";
$(function(){
doWcf(wcfAddress);
});
function doWcf(wcfUrl){
$.ajax({
type: "GET",
contentType: "application/json",
url: wcfUrl,
success: function(store){
hideProgress();
var view_data = store.GetStoreStateResult;
if (view_data.length < 0) {
$("#store_info").empty();
$("#store_info").html("sorry,not found record.");
return;
}
var total_div=$("<div></div>");
total_div.html("total "+view_data.length+" records").css({"color":"#ff0000"});
$("#store_info").append(total_div);
for (var i = 0; i < view_data.length; i++) {
var $details_div=$("<div></div>");
$details_div.html("<b>product name:</b><br>"+view_data[i]["product_name"]
+"<br><b>product barcode:</b><br>"+view_data[i]["product_barcode"]
+"<br><b>into store:</b><br>"+view_data[i]["in_num"]
+"<br><b>out store:</b><br>"+view_data[i]["out_num"]).css({"border-bottom":"1px solid #ff0000"});
$("#store_info").append($details_div);
}
},
headers:{"Authorization":"sang/jw501"},
beforeSend: function(){
showProgress();
},
error: function(xhr){
hideProgress();
alert(xhr.responseText);
}
});
}
</script>
</body>
</html>
3.in android,if use httpclient class,do post or do get,you add post.setHeader("Authorization","sang/jw501"),for example:
public String doPost(String wcfUrl, JSONObject jsonObject) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost();
HttpEntity httpEntity;
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpEntity = stringEntity;
post.setEntity(httpEntity);
post.setURI(new URI(wcfUrl));
post.setHeader("Content-type", "application/json");
post.setHeader("Authorization","sang/jw501");
response = httpClient.execute(post);
return parseHttpResponse(response);
}